from control.models import *
from literature.models import *
import pandas as pd
from django.db import IntegrityError, transaction
import json
from tqdm import tqdm
import traceback
from datetime import datetime
from basic_component_related_management.models import *


def init_variable_data():
    super_admin_entity = User.objects.filter(user_account="superadmin").first()
    unit_file_path = "files/basic_data_init_final_v2/A078. PCdata基表-6-约束和变量表（20250403R1）-0版.xlsx"
    # unit_file_path = "files/basic_data_init_final_v1/基表20250306/A075test.xlsx"
    sheet_name = "变量和约束表"
    df = pd.read_excel(unit_file_path, sheet_name=sheet_name, header=1, dtype=str)
    start_row = 0
    end_row = 51
    # end_row = 13
    num_columns = 10
    selected_data = df.iloc[start_row:, :num_columns].fillna("")
    # print(selected_data)
    quantity_miss_entity = Quantity.objects.filter(quantity_name="未找到的量").first()

    variable_entity_list = []
    for index, row in tqdm(selected_data.iterrows(), desc="Processing variable data"):
        nVariableID = row["nVariableID"]
        sVariableSymbol = row["sVariableSymbol"]
        sVariableName = row["sVariableName"]
        sVariableName_CN = row["sVariableName CN"]
        sVarDescribing = row["sVarDescribing"]
        sVarDescribingCN = row["sVarDescribingCN"]
        sQuantityAbb = row["sQuantityAbb"]
        if sQuantityAbb=="":
            quantity_entity = quantity_miss_entity
        else:
            quantity_entity = Quantity.objects.filter(quantity_abbreviation=row["sQuantityAbb"]).first()
            if quantity_entity is None:
                quantity_entity = quantity_miss_entity
        variable_entity = PropertyVariable(
            name = sVariableName_CN,
            name_en = sVariableName,
            symbol = sVariableSymbol,
            sei_id = nVariableID,
            quantity = quantity_entity,
            pure_used = True,
            binary_used = True,
            ternary_used = True,
            multi_used = True,
            constrain_used = True,
            component_related = True,
            description = sVarDescribingCN,
            description_en = sVarDescribing,
            create_person = super_admin_entity,
            modify_person = super_admin_entity,
        ) 
        variable_entity_list.append(variable_entity)
    try:
        with transaction.atomic():
            PropertyVariable.objects.bulk_create(variable_entity_list)
            # 还需要将所有的物性都与这些变量进行绑定

            property_entity_list = Property.objects.all()
            variable_entity_list1 = PropertyVariable.objects.all()
            property_variable_map = []
            for property_entity in property_entity_list:
                for variable_entity1 in variable_entity_list1:
                    property_variable_map.append(
                        PropertyPropertyVariableMap(
                            property = property_entity,
                            property_variable = variable_entity1
                        )
                    )
            PropertyPropertyVariableMap.objects.bulk_create(property_variable_map)

    except Exception as e:
        traceback.print_exc()
        




def init_variable_content():
    init_variable_data()

    print("variable finish")
